<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { reactive, unref, h, ref, onUnmounted } from 'vue'
import { ElTag } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { DtuListType } from '@/api/scada/type'
import SCADAApi from '@/api/scada'
import { Search } from '@/components/Search'
import DtuDetail from './components/DtuDetail.vue'
import { useIntervalFn } from '@vueuse/core' // 引入 useIntervalFn
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await SCADAApi.GetDtuList({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.rows,
      total: res.total
    }
  },
  immediate: false // 关闭初始化自动请求
})
const { dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    type: 'selection',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    fixed: 'left'
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    fixed: 'left',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'siteName',
    label: t('名称'),
    width: 150,
    form: {
      hidden: true
    },
    table: {
      hidden: false
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'vaguePrice',
    label: t('模糊搜索'),
    width: 150,
    form: {
      hidden: true
    },
    table: {
      hidden: true
    },
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '请输入站点名称或编号'
      }
    }
  },
  {
    field: 'deviceNo',
    label: t('编号'),
    width: 150,
    detail: {
      hidden: false
    },
    table: { hidden: false },
    search: { hidden: true }
  },
  {
    field: 'sampleTime',
    label: t('上传时间'),
    width: 200,
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: { hidden: true }
  },
  {
    field: 'marState',
    label: t('状态'),
    formatter: (_: Recordable, __: any, cellValue: string) => {
      if (cellValue == '0') {
        return h(ElTag, { type: 'primary' }, () => t('在线'))
      } else if (cellValue == '1') {
        return h(ElTag, { type: 'info' }, () => t('离线'))
      } else if (cellValue == '2') {
        return h(ElTag, { type: 'danger' }, () => t('告警'))
      }
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: {
      hidden: false,
      component: 'RadioButton',
      value: '',
      componentProps: {
        options: [
          {
            label: '全部',
            value: ''
          },
          {
            label: '在线',
            value: '0'
          },
          {
            label: '离线',
            value: '1'
          },
          {
            label: '告警',
            value: '2'
          }
        ]
      }
    }
  },
  {
    field: 'dayReports',
    label: t('当日用气量'),
    table: {
      sortable: true
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: { hidden: true }
  },
  {
    field: 'ydayReports',
    label: t('昨日用气量'),
    table: {
      sortable: true
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: { hidden: true }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    fixed: 'right',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: { hidden: true },
    slots: {
      default: (data) => {
        return (
          <>
            <span class="TableBtn" onClick={() => action(data.row)}>
              {t('查看详情')}
            </span>
          </>
        )
      }
    }
  }
])
const { allSchemas } = useCrudSchemas(crudSchemas)
const saveLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('查看详情')
const currentRow = ref<any | null>(null)
//表格操作
const action = (row: DtuListType) => {
  dialogVisible.value = true
  if (row.bsqList && row.lljList) {
    currentRow.value = [row.bsqList, ...row.lljList]
  } else if (row.bsqList && row.lljList == null) {
    currentRow.value = row.bsqList
  } else if (row.lljList && row.bsqList == null) {
    currentRow.value = row.lljList
  }
}
const save = async () => {
  dialogVisible.value = false
}
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
// / 添加定时刷新功能
const { pause } = useIntervalFn(
  () => {
    console.log('🔄 自动刷新表格数据...')
    getList() // 调用表格的刷新方法
  },
  60000, // 60秒 = 1分钟
  {
    immediate: true, // 立即开始执行
    immediateCallback: true // 立即执行回调（首次加载也执行）
  }
)

// 组件卸载时停止定时器
onUnmounted(() => {
  pause()
})
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="uuid"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog
    v-model="dialogVisible"
    class="dialog"
    :title="dialogTitle"
    style="width: 90%"
    maxHeight="500px"
  >
    <DtuDetail :current-row="currentRow" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('提交') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style scoped lang="less">
.el-button {
  margin-top: 10px;
}
:deep(.TableBtn) {
  margin: 0 5px;
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600 !important;
}
:deep(.el-radio-button--small .el-radio-button__inner) {
  padding: 7px 15px !important;
}
:deep(.el-dialog__body) {
  background: rgb(204, 204, 204, 0.5);
  padding: 10px !important;
}
</style>
<style>
.dialog .el-dialog__body {
  background: rgb(204, 204, 204, 0.5);
  padding: 10px !important;
}
</style>
